<script setup>
import {reactive} from "vue";
import {requestAllWares, requestNewOrder, requestNewSale, requestChangeCollect, requestGetInfo} from "@/api";

const beforeClose = (action) =>
    new Promise((resolve) => {
      if (action === 'confirm') {
        dialogGroup.show = false;
        resolve(true);
      } else {
        // 拦截取消操作
        resolve(false);
      }
    })

const dialogGroup = reactive({
  title: "商店",
  message: "默认",
  show: false,
})

const storageGroup = reactive({
  userinfo: uni.getStorageSync("userInfo"),
})

const searchGroup = reactive({
  searchText: "",
  searchWares() {
    waresGroup.currentWares = [];
    for (let ware of waresGroup.wares) {
      if (ware.name.indexOf(this.searchText) !== -1) {
        waresGroup.currentWares.push(ware);
      }
    }
  }
})

const routerGroup = reactive({
  linkItemInfo(ware) {
    uni.navigateTo({url: "../itemInfo/itemInfo?ware=" + JSON.stringify(ware)});
  }
})

const waresGroup = reactive({
  currentWares: [],
  wares: [],
  baseUrl: "http://118.178.254.102:1253/",
  async getWares() {
    this.wares = [];
    let result = await requestAllWares();
    if (result.statusCode === 200) {
      this.wares = result.data;
      this.currentWares = result.data
      orderGroup.initBuyWareNum(result.data);
    }
  },
  getCurrentWares(type) {
    if (type === "全部") {
      this.currentWares = this.wares;
    } else {
      this.currentWares = [];
      for (let ware of this.wares) {
        if (ware.type === type) {
          this.currentWares.push(ware);
        }
      }
    }
  },
})

const orderGroup = reactive({
  buyWaresList: [],
  price: 0,
  initBuyWareNum(wares) {
    for (let i = 0; i <= wares.length; i++) {
      this.buyWaresList[i] = {name: wares[i].name,code:wares[i].code, price: wares[i].price, num: 0};
    }
  },
  getBuyNum(name){
    for (let i = 0; i <= this.buyWaresList.length; i++) {
      if (this.buyWaresList[i].name === name) {
        return this.buyWaresList[i].num;
      }
    }
  },
  async changeCollect(name) {
    if (storageGroup.userinfo.login_state) {
      const result = await requestGetInfo({account: storageGroup.userinfo.account});
      if (result.statusCode === 200) {
        let result2 = null;
        if (result.data[0].collect === "" || result.data[0].collect === null) {
          result2 = await requestChangeCollect({account: storageGroup.userinfo.account, collect: name})
          if (result2.statusCode === 200) {
            if (result2.data === "Normal") {
              dialogGroup.message = "收藏成功";
              dialogGroup.show = true;
            }
          }
        } else {
          if (result.data[0].collect.split("_").indexOf(name) >= 0) {
            dialogGroup.message = "收藏失败，收藏夹中已有该商品";
            dialogGroup.show = true;
          } else {
            result2 = await requestChangeCollect({
              account: storageGroup.userinfo.account,
              collect: result.data[0].collect + "_" + name
            })
            if (result2.statusCode === 200) {
              if (result2.data === "Normal") {
                dialogGroup.message = "收藏成功";
                dialogGroup.show = true;
              }
            }
          }
        }
      }
    }
  },
  addNum(name) {
    for (let buyWare of this.buyWaresList) {
      if (buyWare.name === name) {
        buyWare.num += 1;
        this.updatePrice();
      }
    }
  },
  reduceNum(name) {
    for (let buyWare of this.buyWaresList) {
      if (buyWare.name === name) {
        if (buyWare.num > 0) {
          buyWare.num -= 1;
          this.updatePrice();
        }
      }
    }
  },
  updatePrice() {
    this.price = 0;
    for (let buyWare of this.buyWaresList) {
      this.price = this.price + buyWare.price * buyWare.num * 100;
    }
  },
  submitOrder() {
    if (storageGroup.userinfo.login_state) {
      let wareList = "";
      for (let buyWare of this.buyWaresList) {
        if (buyWare.num > 0) {
          requestNewSale({name: buyWare.name, num: buyWare.num});
          wareList = wareList + buyWare.code + "_";
        }
      }
      if (wareList !== "") {
        requestNewOrder({account: storageGroup.userinfo.account, code: wareList, price: this.price});
        dialogGroup.message = "下单成功";
        dialogGroup.show = true;
      }
    } else {
      dialogGroup.message = "您还未登录，请先登录";
      dialogGroup.show = true;
    }
  }
})
waresGroup.getWares();
</script>

<template>
  <van-dialog
      :before-close="beforeClose"
      :message="dialogGroup.message"
      :show="dialogGroup.show"
      :title="dialogGroup.title"
      custom-class="my-custom-class"
  />
  <view class="shop">
    <view class="top">
      <view class="container-box">
        <view class="top-box">
          <p class="top-box-title">HellShop商城</p>
          <p class="top-box-text">电商联盟，未来不是梦！</p>
        </view>
      </view>
    </view>
    <view class="search">
      <view class="container-box">
        <view class="search-box">
          <van-row>
            <van-col span="18">
              <view class="search-text-box">
                <input class="search-text" type="text" v-model="searchGroup.searchText" placeholder="请输入搜索关键词"
                       style="height: 80rpx;"/>
              </view>
            </van-col>
            <van-col span="6">
              <view class="search-btn-box">
                <button class="search-btn" style="border-radius: 20rpx;background: #66c6f2;"
                        @click="searchGroup.searchWares()">搜索
                </button>
              </view>
            </van-col>
          </van-row>
        </view>
      </view>
    </view>
    <view class="main">
      <van-row>
        <van-col span="6">
          <van-sidebar>
            <van-sidebar-item title="全部" @click="waresGroup.getCurrentWares('全部')"/>
            <van-sidebar-item title="索尼（SONY）" @click="waresGroup.getCurrentWares('索尼（SONY）')"/>
            <van-sidebar-item title="ThinkPad" @click="waresGroup.getCurrentWares('ThinkPad')"/>
            <van-sidebar-item title="埠帝" @click="waresGroup.getCurrentWares('埠帝')"/>
            <van-sidebar-item title="联想（Lenovo）" @click="waresGroup.getCurrentWares('联想（Lenovo）')"/>
            <van-sidebar-item title="PlayStation" @click="waresGroup.getCurrentWares('PlayStation')"/>
          </van-sidebar>
        </van-col>
        <van-col span="18">
          <view v-for="(ware,index) of waresGroup.currentWares" :key="index" @click="routerGroup.linkItemInfo(ware)">
            <van-card
                :num="orderGroup.getBuyNum(ware.name)"
                :tag="ware.type"
                :price="ware.price"
                :desc="'已售：' + ware.sales + '份'"
                :title="ware.name"
                :thumb="waresGroup.baseUrl+ware.img.split('_')[0]"
            >
              <view slot="footer">
                <van-button size="mini" @tap.stop.prevent="orderGroup.changeCollect(ware.name)">☆</van-button>
                <van-button size="mini" @tap.stop.prevent="orderGroup.reduceNum(ware.name)">-</van-button>
                <van-button size="mini" @tap.stop.prevent="orderGroup.addNum(ware.name)">+</van-button>
              </view>
            </van-card>
          </view>
        </van-col>
      </van-row>
      <view class="message"></view>
      <van-row>
        <van-submit-bar
            :price="orderGroup.price"
            @submit="orderGroup.submitOrder()"
            button-text="提交订单"
        />
      </van-row>
    </view>
  </view>
</template>

<style scoped src="../../css/shop.css">

</style>